import React, { Component } from "react";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
import draftToHtml from "draftjs-to-html";
import htmlToDraft from "html-to-draftjs";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

class RichTextEditor extends Component {
  state = {
    editorState: EditorState.createEmpty(),
  };

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState,
    });

    const content = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    //console.log(content);
    this.props.setDetails(content);
  };

  // 将html转换为文本
  setRichText = (html) => {
    const contentBlock = htmlToDraft(html);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(
        contentBlock.contentBlocks
      );
      const editorState = EditorState.createWithContent(contentState);
      this.setState({
        editorState,
      });
    }
  };

  render() {
    const { editorState } = this.state;
    return (
      <div>
        <Editor
          editorState={editorState}
          wrapperClassName="demo-wrapper"
          editorClassName="demo-editor"
          editorStyle={{
            border: "1px solid #d1d1d1",
            paddingLeft: "20px",
            lineHeight: "16px",
            minHeight: "200px",
          }}
          onEditorStateChange={this.onEditorStateChange}
        />
      </div>
    );
  }
}

export default RichTextEditor;
